package com.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/** 获取数据库连接对象的工具类 */
public class SqlSessionGetter {

  private static SqlSessionFactory factory;

  static {
    InputStream is = null;
    try {
      is = Resources.getResourceAsStream("mybatis-config.xml");
    } catch (IOException e) {
      e.printStackTrace();
    }

    factory = new SqlSessionFactoryBuilder().build(is);
    System.out.println(factory.getConfiguration());
  }

  /** 获取数据库连接对象 */
  public static SqlSession getSqlSession() {
    SqlSession session = null;
    if (factory != null) {
      session = factory.openSession();
    }
    return session;
  }
}
